<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import type { ChatMessage, MessageEvent, MessageEndEvent, TtsMessageEvent, TtsMessageEndEvent, MessageReplaceEvent, ErrorEvent } from '../types/chat'
import { useChatStore } from '../stores/chat'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { ChatApiService } from '../services/chatApi'
import { marked } from 'marked'
import { logger } from '../utils/logger'
import { AudioPlayerService } from '../services/audioPlayer'

// 配置marked选项
marked.setOptions({
  breaks: true, // 支持Github风格的换行符
  gfm: true     // 支持Github风格的Markdown
})

// 渲染Markdown为HTML
const renderMarkdown = (text: string): string => {
  if (!text) return '';
  try {
    return String(marked.parse(text));
  } catch (error) {
    logger.error('ChatView', 'Markdown渲染失败', error);
    return text;
  }
}

const route = useRoute()
const chatStore = useChatStore()
const messageInput = ref('')
const messagesContainer = ref<HTMLElement | null>(null)
const messages = ref<ChatMessage[]>([])
const isLoading = ref(false)
const isBlockingLoading = ref(false) // 非流式请求加载状态

// 音频流相关变量
const isReceivingTts = ref(true) // 是否正在接收TTS数据
const isProcessingAudio = ref(false) // 是否正在处理音频

// 初始化简化的音频播放器
const audioPlayer = ref<AudioPlayerService | null>(null)

const MIN_CHUNKS_TO_PROCESS = 3 // 至少累积多少块再处理
const MAX_WAIT_TIME = 300 // 最大等待时间(毫秒)
const lastChunkReceiveTime = ref(0) // 上次接收音频块的时间
const pendingAudioChunks = ref<string[]>([]) // 等待处理的音频块
const processingTimer = ref<number | null>(null) // 处理计时器

// 动画资源
const animations = ref({
  idle: '/idle.gif',
  speaking: '/speaking.gif'
})

const userAvatar = '/user.png'
const aiAvatar = '/ai.png'

// 添加tooltip相关状态
const tooltipVisible = ref(false)
const tooltipContent = ref('')
const tooltip = ref<HTMLElement | null>(null)

// 添加预览弹窗状态
const previewVisible = ref(false)
const previewContent = ref('')

// 添加预览方法
const showPreview = (content: string) => {
  previewContent.value = content
  previewVisible.value = true
}

// 关闭预览
const closePreview = () => {
  previewVisible.value = false
}

// 下载文件方法
const downloadFile = async (dataset_id: string, document_id: string) => {
  try {
    if (!dataset_id || !document_id) {
      throw new Error('缺少必要的参数');
    }
    
    const fileInfo = await chatApiService.downloadFile(dataset_id, document_id);
    
    // 创建一个隐藏的a标签来下载文件
    const link = document.createElement('a');
    link.href = fileInfo.download_url;
    link.download = fileInfo.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage.success('文件下载成功');
  } catch (error) {
    logger.error('ChatView', '下载文件失败', error);
    ElMessage.error(error instanceof Error ? error.message : '下载文件失败');
  }
}

// 计算当前显示的动画
const currentAnimation = ref(animations.value.idle)

// 设置动画状态的回调
const updateAnimation = (animation: string) => {
  currentAnimation.value = animation
}

// 添加 TextDecoder
const decoder = new TextDecoder()

// 处理累积的音频块
const processAudioChunks = () => {
  if (pendingAudioChunks.value.length === 0 || !audioPlayer.value) {
    isProcessingAudio.value = false
    return
  }
  
  // 取出等待处理的音频块
  const audioChunks = [...pendingAudioChunks.value]
  pendingAudioChunks.value = []
  
  // 处理每个音频块
  for (const chunk of audioChunks) {
    audioPlayer.value.appendAudioData(chunk)
  }
  
  // 如果还有更多块且正在接收数据，继续处理
  if (pendingAudioChunks.value.length > 0 && isReceivingTts.value) {
    scheduleAudioProcessing()
  } else {
    isProcessingAudio.value = false
  }
}

// 调度音频处理
const scheduleAudioProcessing = () => {
  if (processingTimer.value !== null) {
    clearTimeout(processingTimer.value)
  }
  
  processingTimer.value = window.setTimeout(() => {
    processAudioChunks()
    processingTimer.value = null
  }, Math.min(MAX_WAIT_TIME, pendingAudioChunks.value.length > 1 ? 0 : 100))
}

// 初始化API服务
const chatApiService = new ChatApiService(
  {
    apiKey: chatStore.config.apiKey,
    dataset_Key: chatStore.config.dataset_Key,
    userId: chatStore.config.userId
  },
  true // 启用调试模式
)

// 获取事件流服务
const eventStreamService = chatApiService.getEventStreamService()

// 当前任务ID
const currentTaskId = ref('')

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim() || isLoading.value) return
  
  // 获取用户输入并清空输入框
  const userMessage = messageInput.value.trim()
  messageInput.value = ''
  
  // 创建用户消息
  const userMessageObj: ChatMessage = {
    id: 'user_' + Date.now(),
    role: 'user',
    content: userMessage,
    timestamp: Date.now(),
    resources: []
  }
  
  // 添加消息到列表
  messages.value.push(userMessageObj)
  scrollToBottom()
  
  // 更新状态
  isLoading.value = true
  
  // 准备发送给AI的消息历史
  const messageHistory = messages.value.slice(-3) // 只取最近3条消息
  
  try {
    // 重置音频播放器
    if (audioPlayer.value) {
      audioPlayer.value.reset()
    }
    
    // 设置事件处理器
    setupEventHandlers()
    
    // 发送消息并获取流式响应
    await chatApiService.sendChatMessage(messageHistory, true) // 启用TTS
  } catch (error) {
    logger.error('ChatView', '发送消息失败', error)
    isLoading.value = false
    ElMessage.error(error instanceof Error ? error.message : '发送失败，请重试')
  }
}

// 取消当前请求
const cancelRequest = async () => {
  if (currentTaskId.value) {
    try {
      await chatApiService.abortRequest(currentTaskId.value)
      isLoading.value = false
      ElMessage.info('已取消当前请求')
    } catch (error) {
      logger.error('ChatView', '取消请求失败', error)
    }
  }
}

// 设置事件处理器
const setupEventHandlers = () => {
  // 消息事件处理
  eventStreamService.onMessage((event: MessageEvent) => {
    // logger.debug('ChatView', '收到message事件', event);
  
    let assistantContent = '';
    let messageId = '';
    
    if ('answer' in event) {
      assistantContent = event.answer || '';
      messageId = event.message_id;
      currentTaskId.value = event.task_id;
    } 
    else if ('id' in event) {
      const oldEvent = event as { id: string; answer?: string; task_id?: string };
      messageId = oldEvent.id;
      assistantContent = oldEvent.answer || '';
      if (oldEvent.task_id) {
        currentTaskId.value = oldEvent.task_id;
      }
    }
    
    if (!messageId) {
      logger.error('ChatView', '无法从消息事件中获取message_id', event);
      return;
    }
    
    // 更新或创建消息
    const existingMessage = messages.value.find((m: ChatMessage) => m.id === messageId);
    if (existingMessage) {
      // 将新内容追加到现有内容
      existingMessage.content += assistantContent;
    } else {
      messages.value.push({
        id: messageId,
        role: 'assistant',
        content: assistantContent,
        timestamp: ('created_at' in event ? event.created_at : Date.now()) * 1000 || Date.now(),
        resources: []
      });
    }
    scrollToBottom();
  });
  
  // 消息结束事件处理
  eventStreamService.onMessageEnd((event: MessageEndEvent) => {
    logger.debug('ChatView', '收到message_end事件', event)
    isLoading.value = false
    
    // 处理元数据和参考资源
    const resources = event.metadata?.retriever_resources || []
    
    // 更新消息的参考资源
    if (resources.length > 0) {
      const targetMessageId = event.message_id
      const existingMessage = messages.value.find((m: ChatMessage) => m.id === targetMessageId)
      if (existingMessage) {
        logger.debug('ChatView', '更新消息的参考资源', { count: resources.length })
        existingMessage.resources = resources
      }
    }
  })
  
  // 音频事件处理
  eventStreamService.onTtsMessage((event: TtsMessageEvent) => {
    if (event.audio) {
      // 添加到待处理队列
      pendingAudioChunks.value.push(event.audio)
      lastChunkReceiveTime.value = Date.now()
      
      // 处理音频数据
      if (pendingAudioChunks.value.length === 1 && !isProcessingAudio.value) {
        isProcessingAudio.value = true
        scheduleAudioProcessing()
      } else if (pendingAudioChunks.value.length >= MIN_CHUNKS_TO_PROCESS) {
        processAudioChunks()
      }
    }
  })
  
  // 音频结束事件处理
  eventStreamService.onTtsMessageEnd((event: TtsMessageEndEvent) => {
    logger.debug('ChatView', '语音合成结束')
    isReceivingTts.value = false
    
    // 处理剩余的音频块
    if (pendingAudioChunks.value.length > 0) {
      processAudioChunks()
    }
    
    // 结束音频流
    if (audioPlayer.value) {
      try {
        audioPlayer.value.endStream()
      } catch (err) {
        logger.error('ChatView', '结束音频流失败', err)
      }
    }
  })
  
  // 消息替换事件处理
  eventStreamService.onMessageReplace((event: MessageReplaceEvent) => {
    if (event.answer) {
      // 更新当前消息
      const existingMessage = messages.value.find((m: ChatMessage) => m.id === event.message_id)
      if (existingMessage) {
        existingMessage.content = event.answer
        scrollToBottom()
      }
    }
  })
  
  // 错误事件处理
  eventStreamService.onError((event: ErrorEvent) => {
    logger.error('ChatView', '接收到错误事件', event)
    isLoading.value = false
    ElMessage.error(event.message || '请求过程中出现错误')
  })
  
  // 心跳事件处理
  eventStreamService.onPing(() => {
    logger.debug('ChatView', '收到ping事件，保持连接')
  })
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

onMounted(() => {
  // 创建音频播放器
  audioPlayer.value = new AudioPlayerService({
    idleAnimation: animations.value.idle,
    speakingAnimation: animations.value.speaking,
    onAnimationChange: updateAnimation
  })
  
  // 初始化欢迎消息
  messages.value.push({
    id: 'welcome',
    role: 'assistant',
    content: '你好！我是AI助手，很高兴为您服务。',
    timestamp: Date.now(),
    resources: []
  })
  
  // 检查URL参数中是否有预设问题
  const questionParam = route.query.q
  if (questionParam && typeof questionParam === 'string') {
    messageInput.value = questionParam
    setTimeout(() => {
      sendMessage()
    }, 300)
  }
})
</script>


<template>
  <div class="guest-chat">
    <!-- 聊天记录区域 -->
    <div class="chat-messages" ref="messagesContainer">

      <!-- 聊天消息 -->
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message"
        :class="message.role"
      >
        <div class="avatar">
          <img :src="message.role === 'user' ? userAvatar : aiAvatar" :alt="message.role" />
        </div>
        <div class="content">
          <div class="text" v-if="message.content" v-html="renderMarkdown(message.content)"></div>
          <div class="references" v-if="message.resources?.length">
            <div class="reference-header">参考源文件：（点击查看分段内容）</div>
            <div class="reference-list">
              <div
                v-for="resource in message.resources"
                :key="resource.document_id"
                class="reference-item"
              >
                <div class="reference-name" @click="showPreview(resource.content)">
                  <i class="el-icon-document"></i>
                  <span>{{ resource.document_name }}</span>
                </div>
                <div
                  class="download-btn"
                  @click.stop="downloadFile(resource.dataset_id, resource.document_id)"
                >
                  <i class="el-icon-download"></i>
                  <span>下载</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部区域 -->
    <div class="chat-bottom">
      <!-- 虚拟人动画 -->
      <div class="avatar-animation">
        <img :src="currentAnimation" alt="Virtual Avatar" class="avatar-gif" />
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <div class="input-wrapper">
          <input
            type="text"
            v-model="messageInput"
            placeholder="请输入问题..."
            @keyup.enter="sendMessage"
          />
          <div class="send-btn" @click="sendMessage">
            <i class="el-icon-position"></i>
            发送
          </div>
        </div>
      </div>
    </div>

    <!-- 添加全局tooltip -->
    <div class="tooltip" ref="tooltip" v-show="tooltipVisible">
      <div class="tooltip-content">{{ tooltipContent }}</div>
    </div>

    <!-- 添加预览弹窗 -->
    <div class="preview-modal" v-if="previewVisible" @click.self="closePreview">
      <div class="preview-content">
        <div class="preview-header">
          <span>内容预览</span>
          <i class="el-icon-close" @click="closePreview"></i>
        </div>
        <div class="preview-body" v-html="renderMarkdown(previewContent)"></div>
      </div>
    </div>
  </div>
  
</template>


<style>
.text {
  padding: 8px 16px;
  background: white;
  border-radius: 12px;
  font-size: 15px;
  line-height: 1.6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.text strong {
  font-weight: 600;
}

.text code {
  font-family: monospace;
  background: #f5f5f5;
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 14px;
  color: #e83e8c;
}

.text pre {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 5px;
  overflow-x: auto;
  margin: 8px 0;
}

.text pre code {
  background: transparent;
  padding: 0;
  color: #333;
}

.text a {
  color: #2d8cf0;
  text-decoration: none;
}

.text a:hover {
  text-decoration: underline;
}

.text blockquote {
  border-left: 3px solid #ddd;
  padding-left: 12px;
  color: #666;
  margin: 8px 0 8px 0;
}

.text ul, .text ol {
  margin: 8px 0;
  padding-left: 24px;
}

.text h1, .text h2, .text h3, .text h4, .text h5, .text h6 {
  margin: 12px 0 8px 0;
  font-weight: 600;
}

.text h1 {
  font-size: 1.75em;
}

.text h2 {
  font-size: 1.5em;
}

.text h3 {
  font-size: 1.25em;
}

.text hr {
  border: none;
  border-top: 1px solid #eee;
  margin: 10px 0;
}

.text table {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}

.text th, .text td {
  border: 1px solid #ddd;
  padding: 6px 10px;
  text-align: left;
}

.text th {
  background: #f5f5f5;
  font-weight: 600;
}

.message.user .text {
  background: #73899681;
  color: #fff;
}

.message.user .text code,
.message.user .text pre {
  background: rgba(255, 255, 255, 0.2);
}

.message.user .text a {
  color: #fff;
  text-decoration: underline;
}

.message.user .text blockquote {
  border-left-color: rgba(255, 255, 255, 0.4);
  color: rgba(255, 255, 255, 0.8);
}
</style>

<style scoped>
.guest-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  padding-bottom: 20px;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 30px 5px 30px 5px;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.chat-messages::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 5px;
}

.message.user {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.content {
  max-width: 75%;
}

.chat-bottom {
  position: relative;
  padding: 10px 15px 0px 15px;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, #ffffff 20%);
}

.avatar-animation {
  position: absolute;
  left: 24px;
  bottom: 80px; 
  width: 138px; 
  height: 138px; 
  border-radius: 64px; 
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.avatar-gif {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.chat-input {
  position: relative;
  z-index: 1;
}

.input-wrapper {
  background: white;
  border-radius: 24px;
  padding: 6px 6px 6px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.input-wrapper input {
  flex: 1;
  height: 40px;
  border: none;
  outline: none;
  font-size: 15px;
  color: #333;
  background: transparent;
  padding: 0;
}

.input-wrapper input::placeholder {
  color: #999;
}

.send-btn {
  height: 40px;
  width: 100px;
  color: white;
  border-radius: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
  background: #73899681;
}

.send-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.references {
  margin-top: 8px;
}

.reference-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.reference-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f0f7ff;
  border: 1px solid #bae0ff;
  border-radius: 10px;
  transition: all 0.2s ease;
  overflow: hidden;
  width: 100%;
  padding: 4px 0;
  position: relative;
}

.reference-name {
  flex: 1;
  padding: 0 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  color: #2d8cf0;
  cursor: pointer;
  max-width: calc(100% - 70px);
  min-width: 0;
  font-size: 12px;
}

.reference-name span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}

.reference-name i {
  flex-shrink: 0;
  margin-right: 4px;
  font-size: 12px;
}

.download-btn {
  padding: 4px 8px;
  color: #2d8cf0;
  cursor: pointer;
  border-left: 1px solid #bae0ff;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
  min-width: 70px;
  justify-content: center;
  flex-shrink: 0;
  font-size: 12px;
  position: relative;
  z-index: 1;
}

.download-btn:hover {
  background: #e6f4ff;
}

.reference-item:hover {
  background: #e6f4ff;
  border-color: #91caff;
}

.tooltip {
  position: fixed;
  width: 300px;
  padding: 12px;
  background: white;
  border-radius: 6px;
  font-size: 13px;
  line-height: 1.6;
  color: #333;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 9999;
  pointer-events: none;
  border: 1px solid #eee;
  overflow: hidden; /* 确保圆角边框可见 */
}

.tooltip-content {
  max-height: 200px; /* 与 JS 中设置的最大高度相同 */
  overflow-y: auto;
  word-break: break-word;
  white-space: pre-wrap;
  padding-right: 8px; /* 为滚动条留出空间 */
}

/* 自定义滚动条样式 */
.tooltip-content::-webkit-scrollbar {
  width: 4px;
}

.tooltip-content::-webkit-scrollbar-track {
  background: transparent;
}

.tooltip-content::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 2px;
}

.tooltip-content::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}

.reference-header {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.reference-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.preview-content {
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  background: white;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.preview-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eee;
}

.preview-header span {
  font-size: 16px;
  font-weight: 500;
}

.preview-header i {
  cursor: pointer;
  padding: 4px;
  color: #999;
}

.preview-body {
  padding: 16px;
  overflow-y: auto;
  flex: 1;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 预览内容的Markdown样式 */
.preview-body pre {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 5px;
  overflow-x: auto;
  margin: 8px 0;
}

.preview-body code {
  font-family: monospace;
  background: #f5f5f5;
  padding: 2px 4px;
  border-radius: 3px;
  font-size: 14px;
  color: #e83e8c;
}

.preview-body pre code {
  background: transparent;
  padding: 0;
  color: #333;
}

.preview-body blockquote {
  border-left: 3px solid #ddd;
  padding-left: 12px;
  color: #666;
  margin: 8px 0;
}

.preview-body a {
  color: #2d8cf0;
  text-decoration: none;
}

.preview-body a:hover {
  text-decoration: underline;
}

.preview-body ul, .preview-body ol {
  padding-left: 24px;
  margin: 8px 0;
}

.preview-body h1, .preview-body h2, .preview-body h3, 
.preview-body h4, .preview-body h5, .preview-body h6 {
  margin: 12px 0 8px 0;
  font-weight: 600;
}

.preview-body::-webkit-scrollbar {
  width: 4px;
}

.preview-body::-webkit-scrollbar-track {
  background: transparent;
}

.preview-body::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 2px;
}

.preview-body::-webkit-scrollbar-thumb:hover {
  background: #ccc;
}

.loading-screen {
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  background: #f5f7fa;
}

.loading-screen .loading-icon {
  font-size: 40px;
  color: var(--el-color-primary);
  animation: rotate 1s linear infinite;
}

.loading-screen span {
  font-size: 14px;
  color: #666;
}
</style>
